import cv2

def process_video(input_file, output_file):
    def move_check(front_mat, after_mat):
        front_gray = cv2.cvtColor(front_mat, cv2.COLOR_BGR2GRAY)
        after_gray = cv2.cvtColor(after_mat, cv2.COLOR_BGR2GRAY)
        diff_gray = cv2.absdiff(front_gray, after_gray)
        _, diff_gray = cv2.threshold(diff_gray, 25, 255, cv2.THRESH_BINARY)
        element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        diff_gray = cv2.erode(diff_gray, element)
        element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 20))
        diff_gray = cv2.dilate(diff_gray, element2)
        contours, _ = cv2.findContours(diff_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        return contours

    cap = cv2.VideoCapture(input_file)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    out = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc(*'XVID'), fps, (frame_width, frame_height))
    skip_next_frame = False
    count = 0
    tempframe = None

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if count == 0:
            contours = move_check(frame, frame)
            tempframe = frame.copy()
        else:
            contours = move_check(tempframe, frame)

        if len(contours) <= 1 and not skip_next_frame:
            out.write(frame)
        else:
            skip_next_frame = True if len(contours) > 1 else False
        tempframe = frame.copy()
        count += 1

    cap.release()
    out.release()
    cv2.destroyAllWindows()

# 初始视频文件
initial_file = "data/test.mp4"

# 处理视频2到3次
for i in range(1, 4):  # 从1到3，共3次
    output_file = f"test{i}.avi"
    process_video(initial_file, output_file)
    initial_file = output_file  # 更新输入文件为上一次的输出文件